{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "face= 1\n",
      "eyes= 2\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "# 步骤 1.load xml文件 2.加载图片 3.灰度处理计算haar特征 4.检测 5.遍历检测结果并用方框标注\n",
    "# load xml文件\n",
    "face_xml = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n",
    "eye_xml = cv2.CascadeClassifier('haarcascade_eye.xml')\n",
    "# 加载图片\n",
    "img = cv2.imread('face.jpg')\n",
    "cv2.imshow('img',img)\n",
    "# 灰度处理计算haar特征,在计算haar特征之前要进行灰度处理\n",
    "gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n",
    "# 检测 参数1：索要检测的灰度图 参数2：缩放系数 参数3：目标大小单位为像素\n",
    "faces = face_xml.detectMultiScale(gray,1.3,5)\n",
    "print('face=',len(faces))\n",
    "# 遍历检测结果并用方框标注\n",
    "index = 0\n",
    "for (x,y,w,h) in faces:\n",
    "    # 绘制方框\n",
    "    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\n",
    "    roi_face = gray[y:y+h,x:x+w]\n",
    "    roi_colorFace = img[y:y+h,x:x+w]\n",
    "    fileName = str(index)+'.jpg'\n",
    "    cv2.imwrite(fileName,roi_colorFace)\n",
    "    index = index + 1 \n",
    "    eyes = eye_xml.detectMultiScale(roi_face)\n",
    "    print('eyes=',len(eyes))\n",
    "    for (eX,eY,eW,eH) in eyes:\n",
    "        cv2.rectangle(img,(x+eX,y+eY),(x+eX+eW,y+eY+eH),(0,255,0),2)\n",
    "cv2.imshow('imgDetect',img)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
